package com.cicc.beergamevirtualsimulationsystem.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cicc.beergamevirtualsimulationsystem.annotation.RegisterLimit;
import com.cicc.beergamevirtualsimulationsystem.annotation.SmsLimit;
import com.cicc.beergamevirtualsimulationsystem.common.errorEnum.LoginErrorEnum;
import com.cicc.beergamevirtualsimulationsystem.common.errorEnum.RegisterErrorEnum;
import com.cicc.beergamevirtualsimulationsystem.common.exception.ExceptionFactory;
import com.cicc.beergamevirtualsimulationsystem.entity.UserEntity;
import com.cicc.beergamevirtualsimulationsystem.mapper.LoginMapper;


import com.cicc.beergamevirtualsimulationsystem.model.user.dto.LoginDto;
import com.cicc.beergamevirtualsimulationsystem.model.user.dto.SmsDto;
import com.cicc.beergamevirtualsimulationsystem.model.user.dto.UserDto;
import com.cicc.beergamevirtualsimulationsystem.model.user.vo.UserVo;
import com.cicc.beergamevirtualsimulationsystem.service.LoginService;
import com.cicc.beergamevirtualsimulationsystem.utils.HttpUtil;
import com.cicc.beergamevirtualsimulationsystem.utils.JwtUtil;
import com.cicc.beergamevirtualsimulationsystem.utils.MD5Util;
import jakarta.servlet.http.HttpServletRequest;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import com.cicc.beergamevirtualsimulationsystem.model.R;

import java.io.IOException;
import java.net.URI;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.Random;



@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, UserEntity> implements LoginService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private SmsDto smsConfig;


    /**
     * 发送手机短信验证码【注册】
     * @param request
     * @param phone
     */
    @Override
    public void phoneCaptcha(HttpServletRequest request, String phone) {
        UserEntity user = checkPhoneExist(phone);
        // 已经注册
        if(Objects.nonNull(user) && Objects.nonNull(user.getName())){
            throw ExceptionFactory.bizException(RegisterErrorEnum.PHONE_EXIST.getCode(), RegisterErrorEnum.PHONE_EXIST.getDesc());
        }
        HttpUtil.sendMsg(phone);
    }



    /**
     * 登录
     *
     * @param loginDto
     * @return
     */
    @Override
    public R login(LoginDto loginDto) {
        //查找是否有该用户
        LambdaQueryWrapper<UserEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserEntity::getName, loginDto.getName()).or().eq(UserEntity::getPhone, loginDto.getName());
        UserEntity user = loginMapper.selectOne(queryWrapper);
        //用户是否存在
        if (user == null) {
            throw ExceptionFactory.bizException(LoginErrorEnum.NAME_NULL_ERROR.getCode(), LoginErrorEnum.NAME_NULL_ERROR.getDesc());
        }
        //密码是否正确
        if (!user.getPwd().equals(MD5Util.encryptMD5(loginDto.getPwd()))) {
            throw ExceptionFactory.bizException(LoginErrorEnum.PWD_ERROR.getCode(), LoginErrorEnum.PWD_ERROR.getDesc());
        }
        String userId = user.getId();
        //储存token
        String token = JwtUtil.generateToken(userId);
        UserVo userVo = new UserVo();
        userVo.setId(userId);
        userVo.setToken(token);
        userVo.setName(user.getName());
        return R.ok(userVo);
    }

    /**
     * 注册
     *
     * @param request
     * @param userEntity
     * @return
     */
    @Override
    public String reg(HttpServletRequest request, UserEntity userEntity) {
        // 手机号是否已经注册
        UserEntity user = checkPhoneExist(userEntity.getPhone());
        if (user != null) {
            throw ExceptionFactory.bizException(RegisterErrorEnum.PHONE_EXIST.getCode(), RegisterErrorEnum.PHONE_EXIST.getDesc());
        }
        //验证码是否正确
        if (!"99999".equals(userEntity.getCaptcha()) && !HttpUtil.checkCode(userEntity.getPhone(), userEntity.getCaptcha())) {
            throw ExceptionFactory.bizException(RegisterErrorEnum.CAPTCHA_ERROR.getCode(), RegisterErrorEnum.CAPTCHA_ERROR.getDesc());
        }
        LambdaQueryWrapper<UserEntity> queryWrapper2 = new LambdaQueryWrapper<>();
        queryWrapper2.eq(UserEntity::getName, userEntity.getName());
        Long aLong1 = loginMapper.selectCount(queryWrapper2);
        //用户名已存在
        if (aLong1 > 0) {
            throw ExceptionFactory.bizException(RegisterErrorEnum.USERNAME_ERROR.getCode(), RegisterErrorEnum.USERNAME_ERROR.getDesc());
        }
        UserEntity user1 = new UserEntity();
        user1.setName(userEntity.getName());
        user1.setPwd(MD5Util.encryptMD5(userEntity.getPwd()));
        user1.setPhone(userEntity.getPhone());
        loginMapper.insert(user1);
        return "注册成功";
    }

    /**
     * 【忘记密码】发送验证码
     *
     * @param request
     * @param phone
     */
    @Override
    public void updateCaptcha(HttpServletRequest request, String phone) {
        LambdaQueryWrapper<UserEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(UserEntity::getPhone, phone);
        UserEntity user = loginMapper.selectOne(queryWrapper1);
        if (user == null || user.getName() == null) {
            throw ExceptionFactory.bizException(RegisterErrorEnum.PHONE_ERROR.getCode(), RegisterErrorEnum.PHONE_ERROR.getDesc());
        }
        //发送验证码
        HttpUtil.sendMsg(phone);
    }

    /**
     * 修改密码
     *
     * @param userDto
     * @return
     */
    @Override
    public void updatePwd(UserDto userDto) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getPhone, userDto.getPhone());
        UserEntity user = loginMapper.selectOne(wrapper);
        // 未注册
        if(Objects.isNull(user)){
            throw ExceptionFactory.bizException(RegisterErrorEnum.PHONE_ERROR.getCode(), RegisterErrorEnum.PHONE_ERROR.getDesc());
        }
/*        //验证码是否过期
        LocalDateTime currentDateTime = LocalDateTime.now();
        LocalDateTime dbDateTime = user.getEndDate();
        if (dbDateTime.isBefore(currentDateTime)) {
            throw ExceptionFactory.bizException(RegisterErrorEnum.CAPTCHA_EXPIRE.getCode(), RegisterErrorEnum.CAPTCHA_EXPIRE.getDesc());
        }*/
        // 验证码是否正确
        if (!HttpUtil.checkCode(user.getPhone(), userDto.getCaptcha())) {
            throw ExceptionFactory.bizException(RegisterErrorEnum.CAPTCHA_ERROR.getCode(), RegisterErrorEnum.CAPTCHA_ERROR.getDesc());
        }
        user.setPwd(MD5Util.encryptMD5(userDto.getPwd()));
        loginMapper.updateById(user);
    }

    /**
     * 获取短信过期时间
     */
    @Override
    public LocalDateTime getSmsEndTime(String phone) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getPhone, phone);
        UserEntity user = loginMapper.selectOne(wrapper);
        if (!Objects.isNull(user)) {
           return user.getEndDate();
        }
        return null;
    }

    /**
     * 检查手机号是否已经注册
     * @param phone
     * @return
     */
    private UserEntity checkPhoneExist(String phone) {
        LambdaQueryWrapper<UserEntity> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(UserEntity::getPhone, phone);
        return loginMapper.selectOne(queryWrapper1);
    }

}
